package com.itany.cloud.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.itany.cloud.global.GlobalSentinelException;
import com.itany.cloud.util.ResponseResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/hello")
public class HelloController {

    // value:指定资源名称
    // blockHandler:指定处理异常的方法。
    // 注意:该方法必须处于当前类中,且方法的返回值必须与当前方法一致,且方法的参数必须包含原方法的参数与BlockException
    @SentinelResource(value = "f1", blockHandler = "handlerException")
    @RequestMapping("/f1")
    public ResponseResult f1() {
        return ResponseResult.success();
    }

    public ResponseResult handlerException(BlockException e) {
        return ResponseResult.fail("Sentinel异常,异常为:" + e);
    }

    @SentinelResource(value = "f2", blockHandler = "handlerException2")
    @RequestMapping("/f2")
    public ResponseResult f2(String name) {
        return ResponseResult.success(name);
    }

    public ResponseResult handlerException2(String name, BlockException e) {
        return ResponseResult.fail("Sentinel异常,异常为:" + e);
    }

    // blockHandlerClass:指定处理Sentinel异常的类是谁
    // blockHandler:指定类中的方法名
    // 如果没有指定blockHandlerClass属性,则表示当前类的方法
    // 如果指定了blockHandlerClass属性,则表示属性值对应的类的方法
    @SentinelResource(value = "f3", blockHandlerClass = GlobalSentinelException.class, blockHandler = "handlerException")
    @RequestMapping("/f3")
    public ResponseResult f3() {
        return ResponseResult.success();
    }

    @RequestMapping("/f4")
    public ResponseResult f4() {
        System.out.println("当前时间:" + System.currentTimeMillis());
        return ResponseResult.success();
    }

    @RequestMapping("/f5/{id}")
    public ResponseResult f5(@PathVariable Integer id) {
        if (id == 1) {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        if (id == 2) {
            int i = 1 / 0;
        }
        return ResponseResult.success();
    }

    @SentinelResource(value = "f6",blockHandler = "handlerException")
    @RequestMapping("/f6")
    public ResponseResult f6(String s1, String s2) {
        return ResponseResult.success("f6执行成功,第一个参数为:" + s1 + ",第二个参数为:" + s2);
    }

    public ResponseResult handlerException(String s1,String s2,BlockException e){
        return ResponseResult.fail("Sentinel热点参数限流");
    }

    @RequestMapping("/f7")
    public ResponseResult f7(){
        return ResponseResult.success("授权成功");
    }

}
